# -*-coding: utf-8 -*-
# by zw on 2017/12/20

import logging
from sanic import response
from utils.mongo import get_env_config_collection, get_app_config_collection, get_global_template_collection
from sanic import Blueprint

bp = Blueprint('global', url_prefix='')
_logger = logging.getLogger(__name__)


@bp.delete("global_template")
async def remove_global_template(request):
    try:
        template_name = request.raw_args['template_name']
        _logger.info("template_name %s host %s", template_name, request.host)
        get_global_template_collection().delete_one({"template_name": template_name})
    except Exception as e:
        _logger.exception("url %s" % request.url)
        return response.json({"code": 4003, "message": "error message %s" % e, "data": {}})
    else:
        return response.json({"code": 0, "message": "remove ok", "data": {}})


@bp.post("global_template")
async def global_template(request):
    try:
        _json = request.json
        template_name = _json["template_name"]
        yaml_str = _json["template"]

        get_global_template_collection().find_one_and_update({"template_name": template_name},
                                                                   {"$set": {"template": yaml_str}},
                                                                   upsert=True)

    except Exception as e:
        _logger.exception("url %s" % request.url)
        _logger.exception(e)
        return response.json({"code": 4003, "message": "error message %s" % e, "data": {}})
    else:
        return response.json({"code": 0, "message": "", "data": {}})


@bp.get("global_template_list")
async def global_template_list(request):
    try:
        template_name = request.raw_args.get("template_name", "")
        page = int(request.raw_args.get("page", 1))
        limit = int(request.raw_args.get("limit", 30))
        cur = get_global_template_collection().find({"template_name": {"$regex": template_name}}, {"_id": 0})
        _count= cur.count()

        cur.skip((page - 1) * limit).limit(limit)
        res = []
        for doc in cur:
            res.append(doc)
        return response.json({"code": 0, "message": "", "data": res, "count": _count})
    except Exception as e:
        _logger.exception("url %s" % request.url)
        return response.json({"code": 4003, "message": "error message %s" % e, "data": {}})
